<template>
  <!-- 顶部导航栏 -->
  <el-card style="height: 80px">
    <el-form :inline="true" class="form">
      <el-form-item label="用户名">
        <el-input placeholder="请输入用户名" v-model="keyword" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :disabled="keyword ? false : true"
          @click="search"
        >
          搜索
        </el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 用户信息表格 -->
  <el-card style="margin-top: 10px">
    <el-button type="primary" icon="Plus" @click="addUser">添加</el-button>
    <el-button
      type="primary"
      icon="Plus"
      :disabled="selectIdArr.length ? false : true"
      @click="deleteSelectUser"
    >
      批量删除
    </el-button>
    <el-table
      border
      style="width: 100%; margin: 10px 0px"
      :data="userList"
      @selection-change="selectChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="#" width="180" type="index" />
      <el-table-column prop="id" label="id" width="180" />
      <el-table-column prop="username" label="用户名字" width="180" />
      <el-table-column prop="name" label="用户名称" width="180" />
      <el-table-column prop="roleName" label="用户角色" width="180" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="300px" align="center" fixed="right">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setRole(row)"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="editUser(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除${row.username}?`"
            width="260px"
            @confirm="DeleteUser(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[1, 2, 3, 4]"
      :background="true"
      layout="prev, pager, next, jumper, -> ,total, sizes"
      :total="total"
      @current-change="getUserList"
      @size-change="changeSize"
    />
  </el-card>

  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-drawer v-model="drawer">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>添加用户</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input
            placeholder="请您输入用户姓名"
            v-model="userParam.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input
            placeholder="请您输入用户昵称"
            v-model="userParam.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" v-if="userParam.id == null">
          <el-input
            placeholder="请您输入用户密码"
            v-model="userParam.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveUser">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <!-- 抽屉结构:用户某一个已有的账号进行职位分配 -->
  <el-drawer v-model="drawer1">
    <template #header>
      <h4>分配角色(职位)</h4>
    </template>
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParam.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            @change="handleCheckAllChange"
            v-model="checkAll"
            :indeterminate="isIndeterminate"
          >
            全选
          </el-checkbox>
          <!-- 显示职位的的复选框 -->
          <el-checkbox-group
            v-model="userRole"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="(role, index) in allRole"
              :key="index"
              :label="role"
            >
              {{ role.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="drawer1 = false">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  reqUserList,
  reqAddOrUpdateUser,
  reqSetUserRole,
  reqAllRole,
  reqDeleteUser,
  reqBatchDeleteUser,
} from '../../../api/acl/user/index'
import type {
  UserListResponseData,
  UserInfoList,
  AllRole,
  SetRoleData,
  AllRoleResponseData,
} from '../../../api/acl/user/type'
import { ElMessage } from 'element-plus'
import useLayOutSettingStore from '../../../store/modules/setting'

let pageNo = ref<number>(1)

let pageSize = ref<number>(10)

let total = ref<number>(0)

let keyword = ref<string>('')

//获取模板setting仓库
let settingStore = useLayOutSettingStore()

// 定义用户信息数据对象，存储分页接口响应数据
let userList = ref<UserInfoList[]>([])

let drawer = ref<boolean>(false)

//控制分配角色抽屉显示与隐藏
let drawer1 = ref<boolean>(false)

//收集顶部复选框全选数据
const checkAll = ref<boolean>(false)

//控制顶部全选复选框不确定的样式
const isIndeterminate = ref<boolean>(true)

//当前用户已有的职位
let userRole = ref<AllRole>([])

//存储全部职位的数据
let allRole = ref<AllRole>([])

//准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<UserInfoList[]>([])

// 定义添加或修改用户信息抽屉数据收集对象
let userParam = reactive<UserInfoList>({
  username: '',
  name: '',
  password: '',
})

// 获取用户列表数据
const getUserList = async (pager = 1) => {
  pageNo.value = pager
  let result: UserListResponseData = await reqUserList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    userList.value = result.data.records
    total.value = result.data.total
  }
}

//分页器下拉菜单发生变化的时候触发
const changeSize = (obj: any) => {
  getUserList()
}

// 添加用户的回调
const addUser = () => {
  drawer.value = true

  //清空数据
  Object.assign(userParam, {
    id: null,
    username: '',
    name: '',
    password: '',
  })
}

// 编辑用户的回调
const editUser = (row: UserInfoList) => {
  drawer.value = true

  // 将已有的用户数据信息对象拷贝给userParam
  Object.assign(userParam, row)
}

//分配角色按钮的回调
const setRole = async (row: UserInfoList) => {
  //存储已有的用户信息
  Object.assign(userParam, row)
  //获取全部的职位的数据与当前用户已有的职位的数据
  let result: AllRoleResponseData = await reqAllRole(userParam.id as number)
  if (result.code == 200) {
    //存储全部的职位
    allRole.value = result.data.allRolesList
    //存储当前用户已有的职位
    userRole.value = result.data.assignRoles
    //抽屉显示出来
    drawer1.value = true
  }
}

// 抽屉的保存按钮的回调
const saveUser = async () => {
  // 保存按钮 更新|添加
  let result = await reqAddOrUpdateUser(userParam)
  if ((result.code = 200)) {
    ElMessage({
      type: 'success',
      message: userParam.id ? '新增成功' : '更新成功',
    })
    drawer.value = false
    getUserList(userParam.id ? pageNo.value : 1)
    //浏览器自动刷新一次
    //window.location.reload();
  } else {
    drawer.value = false
    // 提示消息
    ElMessage({
      type: 'error',
      message: userParam.id ? '新增失败' : '更新失败',
    })
  }
}

//顶部的全部复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  //val:true(全选)|false(没有全选)
  userRole.value = val ? allRole.value : []
  //不确定的样式(确定样式)
  isIndeterminate.value = false
}

//取消按钮的回调
const cancel = () => {
  //关闭抽屉
  drawer.value = false
}

//顶部全部的复选框的change事件
const handleCheckedCitiesChange = (value: string[]) => {
  //顶部复选框的勾选数据
  //代表:勾选上的项目个数与全部的职位个数相等，顶部的复选框勾选上
  checkAll.value = value.length === allRole.value.length
  //不确定的样式
  isIndeterminate.value = value.length !== allRole.value.length
}

//确定按钮的回调(分配职位)
const confirmClick = async () => {
  //收集参数
  let data: SetRoleData = {
    userId: userParam.id as number,
    roleIdList: userRole.value.map((item) => {
      return item.id as number
    }),
  }
  //分配用户的职位
  let result: any = await reqSetUserRole(data)
  if (result.code == 200) {
    //提示信息
    ElMessage({ type: 'success', message: '分配职务成功' })
    //关闭抽屉
    drawer1.value = false
    //获取更新完毕用户的信息,更新完毕留在当前页
    getUserList(pageNo.value)
  }
}

// 删除用户的回调
const DeleteUser = async (id: number) => {
  let result: any = await reqDeleteUser(id)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除用户成功' })
    //删除完毕获取最新的用户列表数据,删除完毕留在当前页
    getUserList(userList.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}

//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
  selectIdArr.value = value
}

//批量删除按钮的回调
const deleteSelectUser = async () => {
  //整理批量删除的参数
  let idsList: any = selectIdArr.value.map((item) => {
    return item.id
  })
  //批量删除的请求
  let result: any = await reqBatchDeleteUser(idsList)
  if (result.code == 200) {
    ElMessage({ type: 'success', message: '删除成功' })
    getUserList(userList.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}

// 搜索按钮的回调
const search = () => {
  // 根据关键字获取相应的用户数据
  getUserList()
  // 清空关键字
  keyword.value = ''
}

// 重置按钮
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
